package com.rrd.hive.udf;

import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Description(
        name = "json_auto_parse",
        value = "_FUNC_(json, path, split='-|-') - Evaluates a list xpath expression",
        extended = "Example:\n> SELECT _FUNC_('{\"a\": {\"b\": {\"c\": 1, \"e\": 2, \"d\": 2}}, \"aa\": {\"bb\": 1}}','a/b');"
)

public class JsonAutoParseUDF extends UDF {


    public JsonAutoParseUDF() {
    }


    public List<Text> evaluate(String json, String path, String split) {
        if (json == null || path == null) {
            return null;
        }
        ArrayList<Text> result = new ArrayList();
        JSONObject obj ;
        try{
            obj = JSON.parseObject(json);
        }catch(Exception e){
            return null;
        }

        if (path.length() > 0){
            for (String node: path.split("/")) {
                obj = obj.getJSONObject(node);
                if (obj == null) {
                    return null;
                }
            }
        }
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            result.add(new Text(entry.getKey() + split + entry.getValue()));
        }
        return result;

    }

    public List<Text> evaluate(String json, String path) {
        String split = "-|-";
        return evaluate(json, path, split);
    }

    public List<Text> evaluate(String json) {
        String split = "-|-";
        String path = "";
        return evaluate(json, path, split);
    }


    public static void main(String[] args) {
        String json = "{\"key\":{\"reducesinkkey0\":\"27285831a55295dc70d03e6a1931497c\",\"reducesinkkey1\":\"27285831a55295dc70d03e6a1931497c\"},\"value\":{\"_col0\":\"HAO_HUAN\",\"_col1\":\"hh_1b0d9df5-87cc-4e43-8abf-ef0fd877fd3d\",\"_col2\":\"whiteListA\",\"_col3\":\"RESULT_VERIFY_WHITE\",\"_col4\":\"14722\",\"_col5\":\"2022-04-12 19:47:00\",\"_col6\":\"{\\\"feature\\\":{\\\"backup\\\":{\\\"realtimeFeatureMerge\\\":\\\"\\\"},\\\"system\\\":{\\\"step\\\":\\\"whiteListA\\\"},\\\"verify_config\\\":{\\\"step\\\":\\\"whiteListA\\\"}}}\"}}";
        List<Text> l1 = new JsonAutoParseUDF().evaluate(json, "value/_col6");
        for (Text a: l1) {
            System.out.println(a);
        }
    }


}